import Vue from 'vue'
import Vuex from 'vuex'
import util from "@/config/util.js"

//按时间push进chatList
// const timePush = (index, message) => {
// 	let left = 0
// 	let right = store.state.chatList[index].messageList.length - 1
// 	if (right < 0) {
// 		store.state.chatList[index].messageList.push(message)
// 		return
// 	}
// 	let i = new Date(store.state.chatList[index].messageList[right].sendDate).getTime()
// 	let x = new Date(message.sendDate).getTime()
// 	if (i < x) {
// 		store.state.chatList[index].messageList.push(message)
// 		return
// 	}
// 	while (left < right) {
// 		let mid = parseInt((left + right) / 2)
// 		i = new Date(store.state.chatList[index].messageList[mid].sendDate).getTime()
// 		if (i >= x) right = mid
// 		else left = mid + 1
// 	}
// 	store.state.chatList[index].messageList.splice(left, 0, message)
// }

const moveToTop = (index) => {
	if (index == 0) return;
	console.log("moveToTop:" + index)
	let obj = {}
	obj = JSON.parse(JSON.stringify(store.state.chatList[index]))
	store.state.chatList.splice(index, 1)
	store.state.chatList.unshift(obj)
	for (var s of store.state.singleChatMap) {
		if (s[1] < index) {
			store.state.singleChatMap.set(parseInt(s[0]), parseInt(s[1] + 1))
		}
	}
	for (var s of store.state.groupChatMap) {
		if (s[1] < index) {
			store.state.groupChatMap.set(parseInt(s[0]), parseInt(s[1] + 1))
		}
	}
	if ('user' in obj) {
		store.state.singleChatMap.delete(parseInt(obj.user.id))
		store.state.singleChatMap.set(parseInt(obj.user.id), 0)
	} else {
		store.state.groupChatMap.delete(parseInt(obj.group.id))
		store.state.groupChatMap.set(parseInt(obj.group.id), 0)
	}
	store.state.timer = new Date().getTime()
}

Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		isLogin: false,
		token: "",
		loading: false,
		// socketTask:null,
		userInfo: null,
		chatList: [],
		socket: null,
		//单人聊天{user:{},unRead:0,messageList:[]}
		//群聊{group:{},unRead:0,messageList:[]}
		//messageList:[message]
		//message:{fromId,toId,messageType,data}
		singleChatMap: null,
		groupChatMap: null,
		friendRequestNum: 0,
		groupRequestNum: 0,
		timer: 0
	},
	mutations: {
		initLoginState(state, socket) {
			state.socket = socket
			console.log("initLoginState")
			if (state.isLogin === true) return;
			let userInfo = uni.getStorageSync("loginState");
			let token = uni.getStorageSync("token");
			if (userInfo !== null && userInfo !== "" && userInfo !== undefined) {
				state.userInfo = userInfo
				state.token = token
				state.isLogin = true
				state.chatList = uni.getStorageSync(state.userInfo.id + "chatList")
				state.groupChatMap = util.jsonToMap(uni.getStorageSync(state.userInfo.id + "groupChatMap"))
				state.singleChatMap = util.jsonToMap(uni.getStorageSync(state.userInfo.id + "singleChatMap"))
				// console.log(state.chatList)
				if (state.chatList === null || state.chatList === undefined || state.chatList === "") {
					state.chatList = []
				}
				if (!socket.is_open_socket) socket.connectSocketInit(); //建立socket
			}
			console.log("用户信息:")
			console.log(state.userInfo)
			console.log("聊天列表:")
			console.log(state.chatList)
		},
		getcode(state, data) {
			state.code = data.code
		},
		login(state, data) {
			let userInfo = data.user
			let token = data.token
			state.userInfo = userInfo
			state.token = token
			uni.setStorageSync("loginState", userInfo);
			uni.setStorageSync("token", token);
			state.isLogin = true;
			state.chatList = uni.getStorageSync(state.userInfo.id + "chatList")
			state.groupChatMap = util.jsonToMap(uni.getStorageSync(state.userInfo.id + "groupChatMap"))
			state.singleChatMap = util.jsonToMap(uni.getStorageSync(state.userInfo.id + "singleChatMap"))
			console.log(state.chatList)
			if (state.chatList === null || state.chatList === undefined || state.chatList === "") {
				state.chatList = []
			}
		},
		updateUserInfo(state, userInfo) {
			state.userInfo = userInfo;
			uni.setStorageSync("loginState", userInfo);
		},
		logout(state) {
			console.log("logout")
			state.socket.close()
			state.isLogin = false;
			// uni.removeStorage({
			// 	key: state.userInfo.id + "chatList"
			// })
			state.friendRequestNum = 0
			state.groupRequestNum = 0
			state.userInfo = null;
			uni.removeStorage({
				key: "loginState"
			})
			uni.removeStorage({
				key: 'token'
			})

		},
		addMessage(state, message) {
			let self = this
			let toId = message.toId
			let fromId = message.fromId
			// console.log(message)
			//接收的自己发送给服务器,返回的完整信息
			let index
			if (fromId === state.userInfo.id) {
				index = util.findIdAndAdd(toId)
				console.log(index)
				state.chatList[index].messageList.push(message)
				// timePush(index, message)
			} else {
				//接收的别人发送给我的信息
				index = util.findIdAndAdd(fromId)
				console.log(index)
				state.chatList[index].messageList.push(message)
				// timePush(index, message)
				state.chatList[index].unRead += 1
			}
			// moveToTop(index)
			this.commit("storeChatList")
		},
		addGroupMessage(state, message) {
			let fromId = message.fromId
			let index = util.findGidAndAdd(message.toId)
			state.chatList[index].messageList.push(message)
			if (fromId !== state.userInfo.id) {
				state.chatList[index].unRead += 1
			}
			// moveToTop(index)
			this.commit("storeChatList")
		},
		deleteChat(state, index) {
			if ('user' in state.chatList[index]) {
				state.singleChatMap.delete(parseInt(state.chatList[index].user.id))
			} else {
				state.groupChatMap.delete(parseInt(state.chatList[index].group.id))
			}
			for (var s of state.singleChatMap) {
				if (s[1] > index) {
					state.singleChatMap.set(parseInt(s[0]), parseInt(s[1] - 1))
				}
			}
			for (var s of state.groupChatMap) {
				if (s[1] > index) {
					state.groupChatMap.set(parseInt(s[0]), parseInt(s[1] - 1))
				}
			}
			state.chatList.splice(index, 1)
			state.timer = new Date().getTime()
			this.commit("storeChatList")
		},
		friendRequest(state, num) {
			// console.log(num)
			state.friendRequestNum += num
			this.commit("setTabBar")
		},
		groupRequest(state, num) {
			state.groupRequestNum += num
			this.commit("setTabBar")
		},
		subFriendRequestNum(state) {
			state.friendRequestNum = state.friendRequestNum - 1
			this.commit("setTabBar")
		},
		subGrouopRequestNum(state) {
			state.groupRequestNum = state.groupRequestNum - 1
			this.commit("setTabBar")
		},
		setTabBar(state) {
			console.log("friendRequest:" + state.friendRequestNum)
			console.log("groupRequest:" + state.groupRequestNum)
			let num = state.friendRequestNum + state.groupRequestNum
			if (num > 0) {
				uni.setTabBarBadge({
					index: 1,
					text: num.toString()
				})
			} else {
				uni.removeTabBarBadge({
					index: 1
				})
			}
		},
		clearUnread(state, index) {
			// let index = findId(friendId, state.chatList)
			state.chatList[index].unRead = 0
			this.commit("storeChatList")
		},
		storeChatList(state) {
			// console.log(state.chatList)
			uni.setStorage({
				key: state.userInfo.id + "chatList",
				data: state.chatList
			})
			uni.setStorage({
				key: state.userInfo.id + "singleChatMap",
				data: util.mapToJson(state.singleChatMap)
			})
			uni.setStorage({
				key: state.userInfo.id + "groupChatMap",
				data: util.mapToJson(state.groupChatMap)
			})
		},
	},
	actions: {}
})
export default store
